package io.renren.modules.avanotes.controller;

import cn.hutool.core.io.FileUtil;
import io.renren.common.utils.BizUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.vo.input.KeywordDetailVo;
import io.renren.modules.avanotes.entity.LocalMarkdownNotesEntity;
import io.renren.modules.avanotes.service.LocalMarkdownNotesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;


/**
 * 本地笔记表
 *
 * @author zzr
 * @email 529742454@qq.com
 * @date 2022-01-24 22:50:09
 */
@RestController
@RequestMapping("avanotes/localmarkdownnotes")
@Api("本地笔记表接口")
public class LocalMarkdownNotesController {
    @Autowired
    private LocalMarkdownNotesService localMarkdownNotesService;

    //region 信息检索

    @PostMapping("/keywordSearch")
//    @RequiresPermissions("avanotes:localmarkdownnotes:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "key", value = "检索关键字", paramType = "query", dataType = "String")
    })
    @ApiOperation("查询列表")
    public R keywordSearch(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageUtils page = localMarkdownNotesService.keywordSearch(params);
        return R.ok().setData(page);
    }

    @PostMapping("/keywordDetail")
    //@RequiresPermissions("avanotes:localmarkdownnotes:info")
    @ApiOperation("查询单条命中详情")
    public R keywordDetail(@RequestBody KeywordDetailVo vo) {
        String content = localMarkdownNotesService.findKeywordDetail(vo.getId(), vo.getKey());

        //return R.ok().put("localMarkdownNotes", localMarkdownNotes);
        return R.ok().setData(content);
    }


    @PostMapping("/synonymSearch")
//    @RequiresPermissions("avanotes:localmarkdownnotes:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "key", value = "检索关键字", paramType = "query", dataType = "String")
    })
    @ApiOperation("同义词查询")
    public R synonymSearch(@ApiIgnore @RequestParam Map<String, Object> params) throws IOException {
        PageUtils page = localMarkdownNotesService.synonymSearch(params);
        return R.ok().setData(page);
    }

    @PostMapping("/synonymDetail")
    //@RequiresPermissions("avanotes:localmarkdownnotes:info")
    @ApiOperation("查询单条命中详情")
    public R synonymDetail(@RequestBody KeywordDetailVo vo) throws IOException {
        String content = localMarkdownNotesService.findSynonymDetail(vo.getId(), vo.getKey());

        //return R.ok().put("localMarkdownNotes", localMarkdownNotes);
        return R.ok().setData(content);
    }

    //endregion

    /***
     * 上传文件新增
     * noteme 不能使用 RequestBody
     * @param dirPath   目录路径
     * @param file
     * @return
     */
    @PostMapping("/insert")
    @ApiOperation("文件上传")
    public R insert(@RequestParam("dirPath")@NotBlank String dirPath,
                    @RequestParam("file") MultipartFile file) throws IOException {
//        MultipartFile file = param.getFile();
        if (file.isEmpty()) {
            return R.error("上传失败，请选择文件！");
        }
        dirPath = URLDecoder.decode(dirPath, "utf-8");
        String pathPre = "D:\\my-notes\\";
        if (!dirPath.contains(pathPre)) {
            return R.error("路径前缀错误！");
        }
        String fileName = file.getOriginalFilename();
        //region 保存到本地路径的方式

//        String filePath = "/Users/itinypocket/workspace/temp/";
//        File dest = new File(filePath + fileName);
//        try {
//            file.transferTo(dest);
//            return "上传成功";
//        } catch (IOException e) {
//        }
        //endregion


        //region 读取文本内容的方式

        String content = BizUtils.getContentFrom(file);

        //endregion

        String aPath = Paths.get(dirPath, fileName).toString();
        String rPath = aPath.replace(pathPre, "");
        String md5 = DigestUtils.md5DigestAsHex(content.getBytes());
        LocalMarkdownNotesEntity entity = new LocalMarkdownNotesEntity(fileName, aPath, rPath, content, md5);
        localMarkdownNotesService.insertNote(entity);
        return R.ok().setData(entity.getId());
    }

    /**
     * 列表
     */
    @PostMapping("/list")
//    @RequiresPermissions("avanotes:localmarkdownnotes:list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "key", value = "检索关键字", paramType = "query", dataType = "String")
    })
    @ApiOperation("查询列表")
    public R list(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageUtils page = localMarkdownNotesService.searchPage(params);

        //return R.ok().put("page", page);
        return R.ok().setData(page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    //@RequiresPermissions("avanotes:localmarkdownnotes:info")
    @ApiOperation("查询单条")
    public R info(@PathVariable("id") Long id) {
        LocalMarkdownNotesEntity localMarkdownNotes = localMarkdownNotesService.getById(id);

        //return R.ok().put("localMarkdownNotes", localMarkdownNotes);
        return R.ok().setData(localMarkdownNotes);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    //@RequiresPermissions("avanotes:localmarkdownnotes:save")
    //@ApiOperation("保存")
    public R save(@RequestBody LocalMarkdownNotesEntity localMarkdownNotes) {
        localMarkdownNotesService.save(localMarkdownNotes);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    //@RequiresPermissions("avanotes:localmarkdownnotes:update")
    //@ApiOperation("修改")
    public R update(@RequestBody LocalMarkdownNotesEntity localMarkdownNotes) {
        localMarkdownNotesService.updateById(localMarkdownNotes);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    //@RequiresPermissions("avanotes:localmarkdownnotes:delete")
    //@ApiOperation("删除")
    public R delete(@RequestBody Long[] ids) {
        localMarkdownNotesService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
